/**
* Copyright (c) 2018-present, Chen Guodong
* All rights reserved.
*
* @flow
*/
<template>
  <section class="content">
    <!-- 答题卡 -->
    <div v-transfer-dom>
      <x-dialog v-model="datikaVis" class="datika_box">
        <div class="title_box">
          <div class="title">答题卡</div>
        </div>
        <i class="iconfont icon-close close_btn" @click="closeDatika"></i>
        <div class="datika_content">
          <div class="item_box">
            <div class="item_title">单选题</div>
            <div class="item_content">
              <div
                @click="pickerQuestion"
                class="option"
                v-for="(item, index) in 10"
                :key="index"
              >{{item}}</div>
            </div>
          </div>
          <div class="item_box">
            <div class="item_title">多选题</div>
            <div class="item_content">
              <div class="option" v-for="(item, index) in 10" :key="index">{{item}}</div>
            </div>
          </div>
        </div>
        <div class="footer">
          <div class="item complete">已完成</div>
          <div class="item current">当前题目</div>
          <div class="item plan">未做题目</div>
        </div>
      </x-dialog>
    </div>
    <!-- 答题卡 结束 -->
    <Header :title="isExam ? false : type | getCN">
      <div slot="left" @click="goBack" style="width: 100%;height: 100%;text-align: center;">
        <i class="iconfont icon-arrow-left" style="font-size: 22px"></i>
      </div>
      <div class="time_box" slot="middle" v-if="isExam">
        <p class="name">答题时间</p>
        <p class="time">{{time}}</p>
      </div>
      <div slot="right" style="width: 100%;height: 100%;text-align: center;">
        <i
          :class="['iconfont', 'icon-shoucang']"
          style="font-size: 22px;margin-right: 5px;"
          @click="collection"
        ></i>
      </div>
    </Header>
    <div class="main">
      <div class="progress_box">
        <div class="progress">
          <x-progress :percent="((curIndex+1)/total)*100 || 0" :show-cancel="false"></x-progress>
        </div>
        <div class="value">
          <span style="color: red;">{{curIndex+1}}</span>
          /{{total}}
        </div>
      </div>
      <div class="question_box">
        <p class="question">
          <span style="color: red;">【{{curList.type === 1 ? '单选题' : '多选题'}}】</span>
          {{curList.title}}。
        </p>
        <div class="option_box">
          <div
            :class="curOptionClass(index)"
            v-for="(item, index) in curOptions"
            :key="index"
            @click="handlerOption(index)"
          >
            <div class="left">
              <p>{{answerIndex[index]}}</p>
            </div>
            <div class="right">{{item}}</div>
          </div>
        </div>
      </div>
      <div class="analysis-box" v-if="isDone">
        <p>
          您的答案:
          <span style="padding-left: 6px;">{{curList.answered.join(',')}}</span>
        </p>
        <p>
          正确答案:
          <span style="padding-left: 6px;color: green;">{{curList.answer.join(',')}}</span>
        </p>
        <div class="analysis">
          <p class="ana-title">
            <i class="iconfont icon-tixingtishi"></i>答案解析
          </p>
          <p class="ana-main">解析:{{curList.remark || '无'}}</p>
        </div>
      </div>
    </div>
    <div class="footer_box">
      <div class="left" @click="handlerBack">
        <i class="iconfont icon-arrowleft"></i>
        <p>上题</p>
      </div>
      <div class="middle">
        <!-- <div class="datika" @click="showDatika" v-if="isExam">
          <i class="iconfont icon-datiqia"></i>
          <p>答题卡</p>
        </div>-->
        <div class="submit_box" @click="jiaojuan" v-if="!isDone">
          <div class="submit_btn">立即交卷</div>
        </div>
        <div class="submit_box" @click="goScore" v-else>
          <div class="submit_btn">查看成绩单</div>
        </div>
      </div>
      <div class="right" @click="handlerNext">
        <i class="iconfont icon-arrowright1"></i>
        <p>下题</p>
      </div>
    </div>
  </section>
</template>
<script>
import Header from "../../components/Header/Header";
import { XProgress, XDialog, TransferDomDirective as TransferDom } from "vux";
import {
  calendar_qus,
  calendar_save_one,
  calendar_submit,
  plan_qus,
  plan_save_one,
  plan_submit,
  chapter_qus,
  chapter_save_one,
  chapter_submit,
  dayly_qus,
  dayly_save_one,
  dayly_submit,
  exercise_qus,
  exercise_save_one,
  exercise_submit,
  reqCollection,
  calendar_view,
  plan_view,
  chapter_view,
  dayly_view,
  exercise_view
} from "../../api/index.js";
import { numToABC, ABCToNum } from "../../util/unit.js";
import _ from "lodash";

let reqLis = {
  view: {
    calendar: calendar_view,
    plan: plan_view,
    chapter: chapter_view,
    dayly: dayly_view,
    exercise: exercise_view
  },
  start: {
    calendar: calendar_qus,
    plan: plan_qus,
    chapter: chapter_qus,
    dayly: dayly_qus,
    exercise: exercise_qus
  },
  save_one: {
    calendar: calendar_save_one,
    plan: plan_save_one,
    chapter: chapter_save_one,
    dayly: dayly_save_one,
    exercise: exercise_save_one
  },
  submit: {
    calendar: calendar_submit,
    plan: plan_submit,
    chapter: chapter_submit,
    dayly: dayly_submit,
    exercise: exercise_submit
  }
};

export default {
  data() {
    return {
      info: {}, //整体题目的基本信息
      type: "",
      // isDone: false,
      answerIndex: ["A", "B", "C", "D", "E", "F", "G"],
      title: "",
      // isExam: 1, //isExam 1不是考试 2是考试
      data: [],
      total: 0, //题目总数
      curIndex: 0, //当前题号
      time: "00:00:00",
      datikaVis: false, //答题卡是否可见
      selected: "",
      answered: []
    };
  },
  directives: {
    TransferDom
  },
  computed: {
    isExam: function() {
      let type = this.type;
      if (type === "calendar" || type === "plan") {
        return true;
      } else {
        return false;
      }
    },
    curList: function() {
      return this.data[this.curIndex] || {};
    },
    curOptions: function() {
      let a = this.curList;
      if (a && a.options) {
        let r = [];
        for (let i in a.options) {
          r.push(a.options[i]);
        }
        return r;
      } else {
        return [];
      }
    },
    curSelected: function() {
      let a = this.curList;
      return a.selected || [];
    },
    curAnswered: function() {
      let r = [];
      if (this.isDone) {
        r = ABCToNum(this.curList.answer);
      } else {
        let hisAnswered = this.curList.answered;
        // if (hisAnswered && hisAnswered.length > 0 && this.answered[this.curIndex] && this.answered[this.curIndex].length<1) {
        //   r = ABCToNum(hisAnswered);
        // } else {
        r = this.answered[this.curIndex] || [];
        // }
      }
      return r;
    },
    isAnalysis: function() {
      return this.curList.viewAble;
    },
    isDone: function() {
      let status = this.info.status;
      if (status === 1) {
        return true;
      } else {
        return false;
      }
    }
  },
  watch: {
    curOptions: function(data) {},
    curIndex: function(newData, oldData) {
      this.saveAnswer(oldData);
    }
  },
  mounted() {
    this.type = this.$router.history.current.query.type;
    // this.isExam = this.$router.history.current.query.isExam;
    this.title = this.$router.history.current.query.title;
    this.getQuestion();
  },
  methods: {
    // collection
    async collection() {
      let isExam = this.$router.history.current.query.isExam;
      let result = await reqCollection({
        relid: this.curList.id,
        type: isExam == "1" ? "EXAM" : "QUSTION"
      });
      if (result.code === 1) {
        this.$vux.toast.show(`收藏成功!`);
      } else {
        this.$vux.toast.show(`收藏失败!`);
      }
    },
    curOptionClass(index) {
      if (this.curAnswered.indexOf(index) != -1) {
        // 被选中
        if (this.isDone) {
          return "option selected analysis";
        } else {
          return "option selected";
        }
      } else {
        return "option";
      }
      // ['option', curAnswered.indexOf(index) != -1 ? 'selected' : '']
    },
    // 保存单个题目的答案
    async saveAnswer(index, callback) {
      let a = this.answered[index];
      if (this.type === "exercise") {
        this.data[index] = { ...this.curList, answered: numToABC(a) };
        console.log("this.data[index]", this.data[index]);
        return;
      }
      if (a && a.length > 0) {
        let params = {
          id: this.data[index].id,
          answers: numToABC(a).join(",")
        };
        let result = await reqLis["save_one"][this.type](params);
        if (result.code === 1) {
          console.log("提交成功", result.data);
          callback && callback();
        } else {
          this.$vux.toast.show(`提交第${index + 1}题答案失败:${result.msg}`);
        }
      } else {
        console.log("没有选中答案不提交");
        return false;
      }
    },
    // 获取所有答题
    async getQuestion() {
      let p = JSON.parse(localStorage.getItem("selectedProject"));
      let id = this.$router.history.current.query.id;
      let status = this.$router.history.current.query.status;
      let result;
      if (status && status == 1) {
        result = await reqLis["view"][this.type]({ examId: id, sid: p.id });
      } else {
        result = await reqLis["start"][this.type]({
          examId: id,
          sid: p.id
        });
      }
      if (result.code === 1) {
        this.total = result.data.total;
        this.data = result.data.items;
        this.info = result.data.info;
      } else {
        this.$vux.toast.show(`获取试题失败:${result.msg}`);
        this.$router.go(-1);
      }
    },
    startTime() {
      let self = this;
      var hour, minute, second; //时 分 秒
      hour = minute = second = 0; //初始化
      var millisecond = 0; //毫秒
      var int;

      function start() {
        //开始
        int = setInterval(timer, 50);
      }

      function timer() {
        //计时
        millisecond = millisecond + 50;
        if (millisecond >= 1000) {
          millisecond = 0;
          second = second + 1;
        }
        if (second >= 60) {
          second = 0;
          minute = minute + 1;
        }

        if (minute >= 60) {
          minute = 0;
          hour = hour + 1;
        }
        self.time =
          (hour < 10 ? `0${hour}` : hour) +
          ":" +
          (minute < 10 ? `0${minute}` : minute) +
          ":" +
          (second < 10 ? `0${second}` : second);
      }
      start();
    },
    jiaojuan() {
      const self = this;
      this.$vux.confirm.show({
        content: "确认交卷吗?",
        onCancel() {
          console.log("plugin cancel");
        },
        async onConfirm() {
          let a = self.answered[self.curIndex];
          if (a && a.length > 0) {
            let params = {
              id: self.curList.id,
              answers: numToABC(a).join(",")
            };
            let result = await reqLis["save_one"][self.type](params);
            if (result.code === 1) {
              console.log("提交成功", result.data);
              self.submit();
            } else {
              self.$vux.toast.show(
                `提交第${index + 1}题答案失败:${result.msg}`
              );
            }
          } else {
            self.submit();
            return false;
          }
        }
      });
    },
    async submit() {
      if (this.type === "exercise") {
        this.info = { ...this.info, status: 1 };
        console.log("this.info", this.info);
        return;
      }
      let result = await reqLis["submit"][this.type]({
        examId: this.$router.history.current.query.id
      });
      if (result.code === 1) {
        this.$vux.toast.show(`交卷成功`);
        let id = this.$router.history.current.query.id;

        this.$router.push({
          path: "/score",
          query: { id: id, type: this.type }
        });
      } else {
        this.$vux.toast.show(`交卷失败:${result.msg}`);
      }
    },
    closeDatika() {
      this.datikaVis = false;
    },
    pickerQuestion() {
      this.datikaVis = false;
    },
    showDatika() {
      console.log("打开答题卡");
      this.datikaVis = true;
    },
    goBack() {
      if (window.history.length <= 1) {
        this.$router.push({ path: "/" });
        return false;
      } else {
        this.$router.go(-1);
      }
    },
    // 点击选项
    handlerOption(data) {
      const self = this;
      const s = this.curAnswered;
      let b = s.indexOf(data);
      let n = _.cloneDeep(s);
      let status = this.$router.history.current.query.status;
      if (status == 1) {
        return false;
      }
      if (b !== -1) {
        // 已被选中
        _.remove(n, function(n) {
          return n === data;
        });
      } else {
        // 如果max等于1则,去掉第一个再push 如果小于max则push, 如果大于max则警告,
        if (this.curList.type === 1) {
          // 单选
          n.shift();
          n.push(data);
        } else {
          n.push(data);
        }
      }
      this.$set(this.answered, this.curIndex, n);
    },
    handlerBack() {
      if (this.curIndex === 0) {
        this.$vux.toast.show(`已经是第一题`);
        return;
      } else {
        this.curIndex = this.curIndex - 1;
      }
    },
    handlerNext() {
      if (this.curIndex + 1 === this.total) {
        this.$vux.toast.show(`已经是最后一题`);
        return;
      } else {
        this.curIndex = this.curIndex + 1;
      }
    },
    goScore() {
      let id = this.$router.history.current.query.id;
      this.$router.push({ path: "/score", query: { id: id, type: this.type } });
    }
  },
  components: { Header, XProgress, XDialog }
};
</script>
<style lang='less' scoped>
@import "../../util/theme.less";

.time_box {
  .be-full();
  .mix-flex-center();
  flex-direction: column;
  position: relative;

  .name {
    height: 16px;
    font-size: 12px;
    color: @font-regular;
  }

  .date {
    flex: 1;
    font-size: 16px;
  }
}

.content {
  .be-full();

  .main {
    width: 100%;
    height: calc(~"100% - 96px");
    position: relative;
    overflow: auto;
    background: @white;
  }
}

.progress_box {
  padding: 8px 15px;
  .mix-flex-center();
  height: 35px;

  .progress {
    flex: 1;
  }

  .value {
    width: 40px;
    font-size: 12px;
    .mix-flex-center();
    color: @font-regular;
  }
}

.question_box {
  width: 100%;
  // max-height: calc(~"100% - 85px");
  overflow: auto;
  background: @white;
  padding: 10px;

  .question {
    padding-bottom: 15px;
  }

  .option_box {
    width: 100%;

    .option {
      width: 100%;
      border: 1px solid @border-base;
      border-radius: 5px;
      box-sizing: border-box;
      .mix-flex-center();
      margin-bottom: 20px;

      .left {
        width: 40px;
        .mix-flex-center();
        font-size: 12px;

        p {
          width: 16px;
          height: 16px;
          line-height: 16px;
          border-radius: 16px;
          border: 1px solid @border-base;
          box-sizing: border-box;
          .mix-flex-center();
          font-size: 12px;
          background: @white;
        }
      }

      .right {
        flex: 1;
        padding: 12px 20px 12px 0;
        box-sizing: border-box;
        font-size: 12px;
      }
    }

    .selected {
      border: 1px solid red;
      color: red;

      .left {
        p {
          border: 1px solid red;
          background: red;
          color: @white;
        }
      }
    }

    .analysis {
      border: 1px solid @green;
      color: @green;
      .left {
        p {
          border: 1px solid @green;
          color: @white;
          background: @green;
        }
      }
    }
  }
}

.footer_box {
  width: 100%;
  height: 50px;
  box-sizing: border-box;
  border-top: 1px solid @border-base;
  background: @white;
  position: absolute;
  left: 0;
  bottom: 0;
  font-size: 12px;
  z-index: 99;
  .mix-flex-center();

  .left,
  .right {
    width: 68px;
    padding: 5px 0;
    height: 100%;
    .mix-flex-center();
    flex-direction: column;
    box-sizing: border-box;

    i {
      font-size: 14px;
    }
  }

  .middle {
    height: 100%;
    flex: 1;
    border: solid @border-base;
    border-width: 0 1px 0 1px;
    .mix-flex-center();

    .datika {
      flex: 1;
      .mix-flex-center();
      flex-direction: column;
      border-right: 1px solid @border-base;
    }

    .submit_box {
      flex: 1;
      .mix-flex-center();
      padding: 15px 20px;
      position: relative;
      box-sizing: border-box;

      .submit_btn {
        width: 100%;
        height: 100%;
        background: red;
        color: @white;
        font-size: 16px;
        border-radius: 5px;
        text-align: center;
      }
    }
  }
}

// 答题卡
.datika_box {
  position: relative;
  width: 100%;
  overflow: auto;

  .close_btn {
    position: absolute;
    top: 10px;
    right: 10px;
  }

  .title_box {
    width: 100%;
    position: absolute;
    top: -15px;
    .mix-flex-center();

    .title {
      width: 35%;
      height: 30px;
      border-radius: 30px;
      line-height: 30px;
      background: @red;
      color: @white;
      text-align: center;
    }
  }

  .datika_content {
    padding: 15px 10px 40px;

    .item_box {
      .item_title {
        text-align: left;
        padding: 10px 0;
      }

      .item_content {
        .mix-flex-center();
        flex-wrap: wrap;
        justify-content: flex-start;

        .option {
          width: 35px;
          height: 35px;
          border-radius: 35px;
          margin-right: 10px;
          margin-bottom: 10px;
          border: 1px solid @border-base;
          .mix-flex-center();
        }
      }
    }
  }

  .footer {
    height: 40px;
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    box-sizing: border-box;
    .mix-flex-center();

    .item {
      flex: 1;
      font-size: 12px;

      &:before {
        content: "";
        width: 12px;
        height: 12px;
        background: @white;
        border-radius: 12px;
        display: inline-block;
        vertical-align: middle;
        margin-right: 5px;
        box-sizing: border-box;
      }
    }

    .complete {
      &:before {
        background: orange;
      }
    }

    .current {
      &:before {
        background: #ccc;
      }
    }

    .plan {
      &:before {
        background: @white;
        border: 1px solid @border-base;
      }
    }
  }
}

.datika_box /deep/ .weui-dialog {
  overflow: auto !important;
}

// 答案解析
.analysis-box {
  padding-top: 10px;
  p {
    padding: 0 10px 10px;
  }
  .analysis {
    padding: 10px;
    background: @white;
    .ana-title {
      color: @primary;
      i {
        padding-right: 6px;
      }
    }
  }
}
</style>
